import { useEffect, useState } from 'react';
import { Button, Upload, Modal } from 'antd';
import { TRMessage } from '#/components';
import {
  DownloadOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';
import { useTRState } from '#/utils/trHooks';
import { TJModel, TjSelect } from '@/pages/ETrade/components';
import { importList, getTemplate } from '../../services';
import styles from './index.less';

const { Dragger } = Upload;

const sheetToJson = (result) => {
  const workbook = XLSX.read(new Uint8Array(result), { type: 'array' });
  // 只针对该页面取第一个名称
  const firstSheetName = workbook.SheetNames[0];
  const worksheet = workbook.Sheets[firstSheetName];
  const list = XLSX.utils.sheet_to_json(worksheet, {
    defval: '',
  });
  return {
    list,
    name: firstSheetName,
  };
};

const ImportBtn = (props) => {
  const { disabled, formChange } = props;

  const [state, setState] = useTRState({
      finallyFile: [], // 最终保存文件
      saveType: 0, // 确认按钮状态
      visible: false, // 导入弹窗展示
      btnLoading: false, // 弹窗确认按钮loading
      longTermType: [
        {
          label: '集中竞价',
          value: 0,
        },
        {
          label: '滚动撮合',
          value: 1,
        },
      ],
      longTermTypeValue: 0,
    }),
    [fileError, setFileError] = useState(null),
    [fileInfo, setFileInfo] = useState(null),
    [errorMsg, setErrorMsg] = useState(['请上传正确模板!']),
    [isShowMore, setIsShowMore] = useState(false);

  const draggerProps = {
    name: 'file',
    multiple: false,
    showUploadList: false,
    accept: '.xls, .xlsx',
    maxCount: 1,
  };

  const _beforeUpload = (file) => {
    if (!file.uid) {
      file.uid = Date.now();
    }
    if (!file.status) {
      file.status = 'done';
    }
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    fileReader.onload = async (event) => {
      const { result } = event.target;
      const { list, name } = sheetToJson(result);

      // 判断是否有“附表”key
      /* let hasKey = false;

      for (let key in list[0]) {
        if (key === '附表') {
          hasKey = true;
          break;
        }
      }

      // 校验首行数据
      if (!name || !hasKey) {
        setFileError(errorMsg);
        if (file.status) {
          file.status = 'error';
        }
        setFileInfo(file);
        return false;
      } */

      setFileInfo(file);
      setState({
        saveType: 1,
        finallyFile: file,
      });
    };
    // 以二进制方式打开文件
    fileReader.readAsArrayBuffer(file);
    return false;
  };

  const onImport = () => {
    // 导入数据
    if (disabled) return TRMessage.info('请联系管理员获取相关权限');
    setState({
      visible: true,
    });
  };

  const onClose = () => {
    setFileInfo(null);
    setFileError(null);
    setState({
      visible: false,
      saveType: 0,
    });
  };

  const importHandle = async () => {
    if (btnLoading) return;
    setState({
      btnLoading: true,
    });
    const { finallyFile } = state;
    const formData = new FormData();
    formData.append('longTermType', state.longTermTypeValue);
    formData.append('file', finallyFile);
    const res = await importList(formData);
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('导入成功');
      formChange();
      onClose();
    } else {
      TRMessage.error(res?.message || '导入失败');
      setFileError(res?.data);
    }
    setState({
      btnLoading: false,
    });
  };

  const formatSize = (size) => {
    if (size < 1024) return `${size} B`;
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
    return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  };

  const handleDelete = () => {
    setFileInfo(null);
    setFileError(null);
    setState({ saveType: 0 });
  };

  const downFile = () => {
    getTemplate(state.longTermTypeValue)
      .then((response) => {
        if (response && !response.statusCode) {
          const url = window.URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute(
            'download',
            `${state.longTermTypeValue === 0 ? '集中竞价' : '滚动撮合'}导入模板.xlsx`,
          );
          document.body.appendChild(link);
          link.click();
          link.remove();
        } else {
          if (response && response.statusCode && response.statusCode !== '1000') {
            TRMessage.error(response.message);
          }
        }
      })
      .catch((error) => {
        TRMessage.error('模板下载失败！');
      });
  };

  const { visible, btnLoading, saveType } = state;
  return (
    <>
      <Button
        style={{ padding: 0 }}
        className={`${disabled && styles.disabled}`}
        type="link"
        icon={<DownloadOutlined />}
        onClick={onImport}
      >
        导入
      </Button>
      <TJModel
        title={'导入'}
        width={500}
        visible={visible}
        onCancel={onClose}
        footer={[
          <Button key="back" onClick={onClose}>
            取消
          </Button>,
          !!saveType && (
            <Button key="submit" type="primary" loading={btnLoading} onClick={importHandle}>
              提交
            </Button>
          ),
        ]}
      >
        <div className={styles.content}>
          <div className={styles.label}>
            交易类型
            <TjSelect
              style={{ width: 160, marginLeft: '10px' }}
              value={state.longTermTypeValue}
              options={state.longTermType}
              showSearch
              onChange={(longTermTypeValue) => setState({ longTermTypeValue })}
            />
          </div>
          <div className={styles.label}>
            导入文件
            <span className={styles.after}>仅支持Excel文件</span>
          </div>
          <div className={styles.label}>
            下载模板
            <span className={styles.down} onClick={downFile}>
              中长期导入模板.xlsx
            </span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column' }}>
            {!fileInfo ? (
              <div
                style={{
                  width: '450px',
                  height: '150px',
                }}
              >
                <Dragger {...draggerProps} beforeUpload={_beforeUpload}>
                  <p className={styles.label}>
                    <span className={styles.down}>点击上传</span>
                    <span className={styles.after_text}>/ 拖拽到此区域</span>
                  </p>
                </Dragger>
              </div>
            ) : (
              <>
                <div
                  className={styles.file_box}
                  style={
                    fileInfo?.status === 'done' && !fileError
                      ? { border: '1px dashed #434343' }
                      : { border: '1px dashed #c12929' }
                  }
                >
                  <div className={styles.file_info}>
                    <p style={{ marginBottom: '10px' }}>
                      {fileInfo?.name}{' '}
                      {fileInfo?.status === 'done' && !fileError ? (
                        <CheckCircleOutlined style={{ color: 'green', marginLeft: '10px' }} />
                      ) : (
                        <ExclamationCircleOutlined style={{ color: 'red', marginLeft: '10px' }} />
                      )}
                    </p>
                    <p className={styles.after_text}>文件大小:{formatSize(fileInfo?.size)}</p>
                    <p className={styles.after_text}>上传日期: {new Date().toLocaleString()}</p>
                    <div>
                      <span className={styles.file_footer} onClick={handleDelete}>
                        删除
                      </span>
                    </div>
                  </div>
                </div>
                {fileError && (
                  <div style={{ color: '#c12929', marginTop: '4px' }}>
                    {JSON.stringify(fileError)?.slice(1, -2).substring(1, 20)}
                    {JSON.stringify(fileError).slice(1, -2)?.length > 20 && (
                      <>
                        ......
                        <span className={styles.more} onClick={() => setIsShowMore(true)}>
                          更多
                        </span>
                      </>
                    )}
                  </div>
                )}
                <Modal
                  width={720}
                  className={styles.modal}
                  centered={true}
                  visible={isShowMore}
                  onOk={() => {
                    setIsShowMore(false);
                  }}
                  onCancel={() => {
                    setIsShowMore(false);
                  }}
                  maskClosable={true}
                  title={
                    <div key="title" className={styles.modal_title}>
                      文件上传错误内容查看
                    </div>
                  }
                >
                  <pre style={{ width: '100%', height: '320px', whiteSpace: 'pre-wrap' }}>
                    {fileError}
                  </pre>
                </Modal>
              </>
            )}
          </div>
        </div>
      </TJModel>
    </>
  );
};

export default ImportBtn;
